
<template>
  <div class="grid-one p-all-10">
    <a-typography-title :heading="6">
      第一步:选择word模板,只支持后缀为.docx的文件
    </a-typography-title>
    <div class="p_r chooseWord row-center-center">
      <div class="column-center-center">
        <icon-file
          v-if="!selectDocxFile"
          style="font-size: 50px; color: #999"
        />
        <icon-file v-else style="font-size: 50px; color: rgb(22, 93, 255)" />
        <a-typography-text v-if="!selectDocxFile"
          >选择.docx文件</a-typography-text
        >
        <a-typography-text v-else style="color: rgb(22, 93, 255)">{{
          selectDocxFile.name
        }}</a-typography-text>
      </div>
      <input
        class="wordInput"
        type="file"
        accept=".docx"
        @change="onFileChange"
      />
    </div>

    <a-typography-title :heading="6">
      第二步:设置多维表格与上传的word文件对应的字段
    </a-typography-title>
    <div class="row-end-center">
      <a-popover trigger="click" position="bl">
        <icon-settings size="20" />
        <template #content>
          <a-checkbox-group
            @change="checkVoid"
            v-model="checkData"
            direction="vertical"
          >
            <a-checkbox
              v-for="(item, index) in fieldList"
              :key="index"
              :value="item.id"
              >{{ item.name }}</a-checkbox
            >
          </a-checkbox-group>
        </template>
      </a-popover>
    </div>
    <a-table
      :columns="columns"
      :loading="tableLoad"
      :data="tableData"
      :pagination="false"
    >
      <template #wordFileName="{ record }">
        <a-input
          v-model="record.wordFileName"
          placeholder="请输入与word中需要替换的字段"
        ></a-input>
      </template>
      <template #delete="{ rowIndex }">
        <icon-minus-circle :size="20" @click="deleteIndex(rowIndex)" />
      </template>
    </a-table>
    <a-typography-title :heading="6">
      第三步:设置导出的文件名字
    </a-typography-title>
    <div class="grid-three" style="grid-template-columns: 1fr 2fr 1fr 50px">
      <a-select
        v-model="filedNameDic.prefix"
        allow-clear
        :options="fieldList"
        :field-names="{ value: 'name', label: 'name' }"
        placeholder="设置前缀"
      ></a-select>
      <a-input
        v-model="filedNameDic.middle"
        placeholder="不填写默认导出时间(例:2023-12-12 12:00:00)"
      ></a-input>
      <a-select
        v-model="filedNameDic.suffix"
        allow-clear
        :options="fieldList"
        :field-names="{ value: 'name', label: 'name' }"
        placeholder="设置后缀"
      ></a-select>
      <a-typography-text>.docx</a-typography-text>
    </div>

    <a-button
      :loading="buttonLoading"
      :disabled="!commitCan"
      type="primary"
      @click="exportVoid"
      >导出word1</a-button
    >
  </div>
</template>

<script setup >
import { bitable } from "@lark-base-open/js-sdk";
import { ref, onMounted, computed, watch } from "vue";
import { exportDocx } from "./superWord.js";
import dayjs from "dayjs";

const buttonLoading = ref(false);
const tableLoad = ref(false);
const fieldList = ref([]);
const tableData = computed(() => fieldList.value.filter((a) => a["show"]));
const checkData = ref([]);
const selectDocxFile = ref("");
const filedNameDic = ref({
  prefix: "",
  middle: "",
  suffix: "",
});

const commitCan = computed(() => {
  if (selectDocxFile.value && tableData.value.length > 0) {
    return true;
  }
  return false;
});
let table = "";
onMounted(async () => {
  tableLoad.value = true;
  table = await bitable.base.getActiveTable();
  const fieldMetaList = await table.getFieldMetaList();
  for (let item of fieldMetaList) {
    item["wordFileName"] = item["name"];
    item["show"] = true;
  }
  fieldList.value = fieldMetaList;
  console.log("fieldMetaList", fieldMetaList);
  tableLoad.value = false;
});
// 选中的文件
function onFileChange(event) {
  selectDocxFile.value = event.target.files[0];
  console.log("dddd", selectDocxFile.value);
}
// 导出word
async function exportVoid() {
  buttonLoading.value = true;
  const recordList = await table.getRecordList();
  const view = await table.getActiveView();
  const recordIdList = await view.getVisibleRecordIdList();
  debugger
  for (const record of recordList) {
    if (!recordIdList.includes(record.id)) {
      continue;
    }
    const cellList = await record.getCellList();

    let dic = {
      fileName: "",
    };
    let names = { prefix: "", middle: "", suffix: "" };

    for (let filedDic of fieldList.value) {
      const cell = cellList.find((a) =>
        a["field"]["context"].includes(filedDic["id"])
      );
      // const cell = await record.getCellByField(filedDic["id"]);
      // const value = await cell.getValue();
      if (!cell) {
        continue;
      }
      const value = cell.val;
      if (!value) {
        return;
      }
      let valueStr = "";
      if (Array.isArray(value)) {
        valueStr = value.map((a) => a["text"]).join("");
      } else {
        valueStr = value["text"];
      }
      names = fixedFileName(valueStr, filedDic);
      dic[filedDic["wordFileName"]] = valueStr;
    }
    dic.fileName = `${names.prefix}${names.middle}${names.suffix}`;
    
    exportDocx(selectDocxFile.value, dic, true);
  }
  buttonLoading.value = false;
}
// 文件名字
function fixedFileName(valueStr, filedDic) {
  let names = { prefix: "", middle: "", suffix: "" };

  if (filedNameDic.value.prefix && filedNameDic.value.prefix == filedDic.name) {
    names.prefix = valueStr;
  }
  if (filedNameDic.value.middle) {
    names.middle = filedNameDic.value.middle;
  } else {
    names.middle = dayjs().format("YYYY-MM-DD HH:mm:ss");
  }
  if (filedNameDic.value.suffix && filedNameDic.value.suffix == filedDic.name) {
    names.suffix = valueStr;
  }
  return names;
}
// 选中
function checkVoid(values) {
  for (let item of fieldList.value) {
    item["show"] = values.includes(item["id"]);
  }
}
watch(
  fieldList,
  () => {
    checkData.value = fieldList.value.map((a) => {
      if (a["show"]) {
        return a["id"];
      }
    });
  },
  { deep: true }
);
const columns = [
  {
    title: "多维表格字段",
    dataIndex: "name",
    align: "center",
  },
  {
    title: "word对应字段",
    dataIndex: "wordFileName",
    slotName: "wordFileName",
    align: "center",
  },
];
</script>



<style >
.chooseWord {
  position: relative;
  width: 100wh;
  height: 120px;
  background: var(--color-neutral-2);
  border: 2px solid var(--color-bg-3);
  border-radius: 10px;
}
.wordInput {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  opacity: 0;
  /* background: red; */
}
</style>
